<template>
	<view>
		{{receiveUser}}
		<view v-for="(item, index) in msgList" :key="index">
			{{item.msg}}
		</view>
		
		<view class="send">
			<input type="text" placeholder="请输入消息" v-model="msg"/>
			<button @click="send">发送</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			msg: '',
			sendOutUser: '',
			receiveUser: '',
			websocket: null,
			data: [],
			msgList: []
		}
	},
	onLaunch: function() {
		console.log('App Launch')
	},
	onLoad(e) {
		this.sendOutUser = e.sendOutUser
		this.receiveUser = e.receiveUser
	},
	onShow: function() {
		console.log('App Show')
		// 创建ws连接
		uni.connectSocket({
			url: 'ws://117.78.5.218:8080/web-socket/' + this.sendOutUser,
		});
		// 监听ws打开状态
		uni.onSocketOpen((res) => {
			// console.log(123);
			console.log('连接成功');
			// 绑定发送id
			// ws链接状态
			setInterval(() => {
				console.log(111)
				uni.sendSocketMessage({
					data: JSON.stringify({
						type: `ping`,
					})
				});
			}, 1500);
			console.log('WebSocket连接已打开！');
		});
		
		let that = this
		// ws监听接受消息
		uni.onSocketMessage((res) => {
			console.log('收到消息',res)
			console.log(JSON.parse(res.data), 'aaaa');
			if (JSON.parse(res.data).type == 'chat') {
				that.msgList.push({
					...JSON.parse(res.data)
				})
				console.log(that.msgList, 'msgList')
			}
		});
		uni.onSocketError((res) => {
			console.log('WebSocket连接打开失败，请检查！', res);
			uni.connectSocket({
				url: 'ws://117.78.5.218:8080/web-socket/' + this.sendOutUser,
			});
		});
		uni.onSocketClose((res) => {
			console.log('WebSocket 已关闭！');
			uni.connectSocket({
				url: 'ws://117.78.5.218:8080/web-socket/' + this.sendOutUser,
			});
		});
		
	},
	onHide: function() {
		console.log('App Hide')
	}
}
</script>

<style lang="scss">

</style>
